<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Login</title>
  <link rel="stylesheet" href="css/common.css">
  <link rel="stylesheet" href="css/login.css">
</head>

<body>
  <!-- 导航栏 -->
  <div class="nav">
    网页聊天
  </div>
  <!-- 主窗口区 -->
  <div class="login-container">
    <div class="login-dialog">
      <h2>登录</h2>

      <div class="row">
        <span>用户名</span>
        <input type="text" id="username">
      </div>

      <div class="row">
        <span>密码</span>
        <input type="password" id="password">
      </div>

      <div class="row-ver">
        <span>验证码</span>
        <input type="text" name="inputCaptcha" id="inputCaptcha">
        <img id="verificationCodeImg" src="/getCaptcha" style="cursor: pointer;" title="看不清？换一张" />
      </div>

      <div class="row-login">
        <button id="submit">登录</button>
      </div>



      <div class="row-register">
        <!-- <button id="submit-register">注册</button> -->
        <a href="register.html">
          注册新账号
        </a>
      </div>

    </div>
  </div>

  <script src="dist/js/jquery.min.js"></script>

  <!-- 利用jquery实现前后端交互 -->
  <script>
    let submitButton = document.querySelector('#submit');
    submitButton.onclick = function () {
      // 1.获取输入框内容
      let username = document.querySelector('#username').value;
      let password = document.querySelector('#password').value;
      if (username == '' || password == '') {
        alert("所输入的账号或者密码不能为空！");
        return;
      }

      // 2.发送Ajax请求进行登录
      // 先验证码验证，再进行账号密码验证
      var inputCaptcha = $("#inputCaptcha").val();
      $.ajax({
        type: "post",
        url: "/checkCaptcha?captchaCode=" + inputCaptcha,
        success: function (result) {
          if (result) {
            $.ajax({
              url: '/login',
              type: 'post',
              data: {
                username: username,
                password: password
              },
              success: function (body) {
                // 3.处理响应
                if (body && body.userId > 0) {
                  alert("登录成功！")
                  location.assign('/client.html');
                } else {
                  alert("账号或者密码错误！");
                }
              }
            });
          } else {
            alert("验证码错误！");
          }
        }
      });
    }

    // let submitRegisterButton = document.querySelector('#submit-register');
    // submitButton.onclick = function () {
    //   location.assign('/register.html');
    // }
    $("#verificationCodeImg").click(function () {
      $(this).hide().attr('src', '/getCaptcha?dt=' + new Date().getTime()).fadeIn();
    });


  </script>
</body>

</html>